package com.imooc.cloud.mall.practice.categoryproduct.config;

import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import java.time.Duration;

/**
 * 描述：     缓存的配置类
 */
@Configuration
@EnableCaching
public class CachingConfig {

    /**
     * 创建一个 RedisCacheManager 实例，用于管理缓存操作。
     *
     * @param connectionFactory Redis 连接工厂，用于创建 Redis 连接
     * @return RedisCacheManager 实例
     */
    @Bean
    public RedisCacheManager redisCacheManager(RedisConnectionFactory connectionFactory) {

        // 创建一个 Redis 缓存写入器，用于向 Redis 中写入缓存数据
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.lockingRedisCacheWriter(connectionFactory);
        // 创建一个默认的 Redis 缓存配置，用于配置缓存的一些参数，如过期时间等
        RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
        cacheConfiguration = cacheConfiguration.entryTtl(Duration.ofSeconds(30));
        // 通过传入 Redis 缓存写入器和缓存配置，创建一个 RedisCacheManager 实例，用于管理缓存操作
        RedisCacheManager redisCacheManager = new RedisCacheManager(redisCacheWriter,
                cacheConfiguration);
        return redisCacheManager;
    }
}
